package com.buaa.divinationmaster.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.LinearLayout;

import androidx.constraintlayout.widget.ConstraintLayout;

/**
 * 屏幕适配工具类
 * 实现真正的单屏适配，确保所有内容在一个屏幕内完整显示
 * 
 * 功能：
 * - 屏幕尺寸检测和分类
 * - 动态调整布局参数
 * - 计算可用内容区域
 * - 智能字体和间距调整
 */
public class ScreenAdaptationUtil {
    
    private static final String TAG = "ScreenAdaptationUtil";
    
    /**
     * 屏幕尺寸分类
     */
    public enum ScreenSize {
        SMALL("小屏", 320, 5.5f, 0.8f),
        MEDIUM("中屏", 480, 6.0f, 1.0f),
        LARGE("大屏", 600, 6.5f, 1.2f),
        XLARGE("超大屏", 720, 7.0f, 1.4f);
        
        private final String name;
        private final int minDpWidth;
        private final float minInchSize;
        private final float scaleFactor;
        
        ScreenSize(String name, int minDpWidth, float minInchSize, float scaleFactor) {
            this.name = name;
            this.minDpWidth = minDpWidth;
            this.minInchSize = minInchSize;
            this.scaleFactor = scaleFactor;
        }
        
        public String getName() { return name; }
        public int getMinDpWidth() { return minDpWidth; }
        public float getMinInchSize() { return minInchSize; }
        public float getScaleFactor() { return scaleFactor; }
    }
    
    /**
     * 内容类型 - 用于计算所需高度
     */
    public enum ContentType {
        TAROT_SPREAD_SELECTION,
        MEIHUA_INPUT_METHODS,
        COIN_THROWING_INTERFACE,
        LENORMAND_CARD_SELECTION,
        RESULT_DISPLAY
    }
    
    /**
     * 获取当前屏幕尺寸分类
     */
    public static ScreenSize getCurrentScreenSize(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        Configuration config = context.getResources().getConfiguration();
        
        // 计算屏幕DP宽度
        float dpWidth = metrics.widthPixels / metrics.density;
        
        // 计算屏幕物理尺寸（英寸）
        float widthInches = metrics.widthPixels / metrics.xdpi;
        float heightInches = metrics.heightPixels / metrics.ydpi;
        float diagonalInches = (float) Math.sqrt(widthInches * widthInches + heightInches * heightInches);
        
        // 根据DP宽度和物理尺寸判断
        if (dpWidth >= 720 && diagonalInches >= 7.0f) {
            return ScreenSize.XLARGE;
        } else if (dpWidth >= 600 && diagonalInches >= 6.5f) {
            return ScreenSize.LARGE;
        } else if (dpWidth >= 480 && diagonalInches >= 6.0f) {
            return ScreenSize.MEDIUM;
        } else {
            return ScreenSize.SMALL;
        }
    }
    
    /**
     * 应用屏幕适配
     */
    public static void applyScreenAdaptation(Activity activity) {
        ScreenSize screenSize = getCurrentScreenSize(activity);
        
        android.util.Log.d(TAG, "检测到屏幕尺寸: " + screenSize.getName());
        
        // 根据屏幕尺寸调整全局设置
        adjustGlobalSettings(activity, screenSize);
        
        // 调整根布局
        View rootView = activity.findViewById(android.R.id.content);
        if (rootView != null) {
            adjustLayoutRecursively(rootView, screenSize);
        }
    }
    
    /**
     * 获取可用内容区域高度
     */
    public static int getAvailableContentHeight(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int screenHeight = metrics.heightPixels;
        
        // 减去状态栏、导航栏、ActionBar的高度
        int statusBarHeight = getStatusBarHeight(context);
        int navigationBarHeight = getNavigationBarHeight(context);
        int actionBarHeight = getActionBarHeight(context);
        
        int availableHeight = screenHeight - statusBarHeight - navigationBarHeight - actionBarHeight;
        
        android.util.Log.d(TAG, "可用内容高度: " + availableHeight + "px");
        return availableHeight;
    }
    
    /**
     * 计算特定内容类型所需的高度
     */
    public static int calculateRequiredHeight(Context context, ContentType contentType) {
        ScreenSize screenSize = getCurrentScreenSize(context);
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        float density = metrics.density;
        
        int baseHeight = 0;
        switch (contentType) {
            case TAROT_SPREAD_SELECTION:
                // Toolbar(56dp) + 问题输入(72dp) + 2x2网格(240dp) + 按钮(64dp) + 边距(48dp)
                baseHeight = (int) ((56 + 72 + 240 + 64 + 48) * density);
                break;
            case MEIHUA_INPUT_METHODS:
                // Toolbar + 问题输入 + 方法选择 + 数字输入 + 按钮
                baseHeight = (int) ((56 + 72 + 180 + 120 + 64 + 48) * density);
                break;
            case COIN_THROWING_INTERFACE:
                // Toolbar + 问题输入 + 硬币区域 + 六爻显示 + 按钮
                baseHeight = (int) ((56 + 72 + 160 + 140 + 64 + 48) * density);
                break;
            case LENORMAND_CARD_SELECTION:
                // 类似塔罗牌但3个选项
                baseHeight = (int) ((56 + 72 + 180 + 64 + 48) * density);
                break;
            case RESULT_DISPLAY:
                // 结果展示页面
                baseHeight = (int) ((56 + 400 + 64 + 48) * density);
                break;
        }
        
        // 根据屏幕尺寸调整
        return (int) (baseHeight * screenSize.getScaleFactor());
    }
    
    /**
     * 调整GridLayout子项大小以适应屏幕
     */
    public static void adjustGridLayoutForScreen(GridLayout gridLayout, Context context) {
        ScreenSize screenSize = getCurrentScreenSize(context);
        
        // 计算可用高度
        int availableHeight = getAvailableContentHeight(context);
        
        // 减去其他组件占用的高度（Toolbar、问题输入、按钮、边距）
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        float density = metrics.density;
        int otherComponentsHeight = (int) ((56 + 72 + 64 + 48) * density);
        
        // GridLayout可用高度
        int gridAvailableHeight = availableHeight - otherComponentsHeight;
        
        // 如果是2x2布局，每个卡片的高度
        int cardHeight = (gridAvailableHeight - (int)(24 * density)) / 2; // 减去边距
        
        android.util.Log.d(TAG, "GridLayout卡片高度设置为: " + cardHeight + "px");
        
        // 应用到所有子卡片
        for (int i = 0; i < gridLayout.getChildCount(); i++) {
            View child = gridLayout.getChildAt(i);
            GridLayout.LayoutParams params = (GridLayout.LayoutParams) child.getLayoutParams();
            params.height = cardHeight;
            child.setLayoutParams(params);
        }
    }
    
    /**
     * 递归调整布局
     */
    private static void adjustLayoutRecursively(View view, ScreenSize screenSize) {
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            
            // 调整当前ViewGroup
            adjustViewGroup(viewGroup, screenSize);
            
            // 递归调整子View
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                adjustLayoutRecursively(viewGroup.getChildAt(i), screenSize);
            }
        }
    }
    
    /**
     * 调整ViewGroup的布局参数
     */
    private static void adjustViewGroup(ViewGroup viewGroup, ScreenSize screenSize) {
        ViewGroup.LayoutParams params = viewGroup.getLayoutParams();
        
        if (params instanceof ConstraintLayout.LayoutParams) {
            // ConstraintLayout特殊处理
            adjustConstraintLayoutParams((ConstraintLayout.LayoutParams) params, screenSize);
        } else if (params instanceof LinearLayout.LayoutParams) {
            // LinearLayout特殊处理
            adjustLinearLayoutParams((LinearLayout.LayoutParams) params, screenSize);
        }
        
        // 调整内边距
        int basePadding = (int) (12 * screenSize.getScaleFactor());
        viewGroup.setPadding(basePadding, basePadding, basePadding, basePadding);
    }
    
    /**
     * 调整ConstraintLayout参数
     */
    private static void adjustConstraintLayoutParams(ConstraintLayout.LayoutParams params, ScreenSize screenSize) {
        // 根据屏幕尺寸调整边距
        int baseMargin = (int) (8 * screenSize.getScaleFactor());
        params.setMargins(baseMargin, baseMargin, baseMargin, baseMargin);
    }
    
    /**
     * 调整LinearLayout参数
     */
    private static void adjustLinearLayoutParams(LinearLayout.LayoutParams params, ScreenSize screenSize) {
        // 根据屏幕尺寸调整边距
        int baseMargin = (int) (8 * screenSize.getScaleFactor());
        params.setMargins(baseMargin, baseMargin, baseMargin, baseMargin);
    }
    
    /**
     * 调整全局设置
     */
    private static void adjustGlobalSettings(Activity activity, ScreenSize screenSize) {
        // 可以在这里设置全局字体缩放等
        android.util.Log.d(TAG, "应用全局设置，缩放因子: " + screenSize.getScaleFactor());
    }
    
    /**
     * 获取状态栏高度
     */
    private static int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return context.getResources().getDimensionPixelSize(resourceId);
        }
        return (int) (24 * context.getResources().getDisplayMetrics().density); // 默认24dp
    }
    
    /**
     * 获取导航栏高度
     */
    private static int getNavigationBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return context.getResources().getDimensionPixelSize(resourceId);
        }
        return (int) (48 * context.getResources().getDisplayMetrics().density); // 默认48dp
    }
    
    /**
     * 获取ActionBar高度
     */
    private static int getActionBarHeight(Context context) {
        int actionBarHeight = 0;
        if (context instanceof Activity) {
            androidx.appcompat.app.ActionBar actionBar = ((androidx.appcompat.app.AppCompatActivity) context).getSupportActionBar();
            if (actionBar != null) {
                actionBarHeight = actionBar.getHeight();
            }
        }
        
        if (actionBarHeight == 0) {
            // 默认ActionBar高度
            actionBarHeight = (int) (56 * context.getResources().getDisplayMetrics().density);
        }
        
        return actionBarHeight;
    }
    
    /**
     * 检查是否为单屏适配
     */
    public static boolean isSingleScreenCompatible(Context context, ContentType contentType) {
        int availableHeight = getAvailableContentHeight(context);
        int requiredHeight = calculateRequiredHeight(context, contentType);
        
        boolean compatible = availableHeight >= requiredHeight;
        
        android.util.Log.d(TAG, String.format("单屏适配检查 - 可用高度: %dpx, 需要高度: %dpx, 兼容性: %s", 
            availableHeight, requiredHeight, compatible ? "是" : "否"));
            
        return compatible;
    }
}
